package com.myplans.client.util;

import java.util.Date;

import com.google.gwt.user.client.Cookies;

public class CookieManager {

	private static final String USERNAME_COOKIE_NAME = "d3E5d3dvbGlLQUVBQUE9PS13N3c4QW13TGF3ZkNydz08";
	private static final String PASSWORD_COOKIE_NAME = "d29YRHU4S0tZaWdCQUFBPS13Nk1hdzZIQ3YxSENsTU90";
	private static final String SESSIONID_COOKIE_NAME = "SESSION_ID";
	private static final CookieManager INSTANCE = new CookieManager();
	private static final int COOKIE_DAYS_ADD = 10;
	
	public static CookieManager getInstance() {
		return INSTANCE;
	}

	public static void setUserLoginCookies(String username, String md5Password) {
		CookieManager.INSTANCE.deleteUserLoginCookies();
		CookieManager.INSTANCE.addCookie(PASSWORD_COOKIE_NAME, md5Password, COOKIE_DAYS_ADD);
		CookieManager.INSTANCE.addCookie(USERNAME_COOKIE_NAME, username, CookieManager.COOKIE_DAYS_ADD);
		CookieManager.INSTANCE.addSessionIdCookie(SESSIONID_COOKIE_NAME, Long.toString(System.currentTimeMillis()),
				COOKIE_DAYS_ADD);

	}

	public static void deleteUserLoginCookies() {
		Cookies.removeCookie(USERNAME_COOKIE_NAME);
		Cookies.removeCookie(PASSWORD_COOKIE_NAME);
		Cookies.removeCookie(SESSIONID_COOKIE_NAME);
	}

	@SuppressWarnings("deprecation")
	private void addCookie(String username, String cookieValue, int maxAge) {
		Date date = new Date();
		date.setDate(date.getDate() + maxAge);
		Cookies.setCookie(username, cookieValue, date);
	}

	private void addSessionIdCookie(String sessionIdName, String cookieValue, int maxAge) {
		Date date = new Date();
		date.setDate(date.getDate() + maxAge);
		Cookies.setCookie(sessionIdName, cookieValue, date);
	}

	public static boolean getUserLoginCookie(String username, String md5Password) {
		if (Cookies.getCookie("username") != null && Cookies.getCookie("password") != null) {
			return true;
		}
		return false;
	}

	public static String getUsername() {
		return Cookies.getCookie(USERNAME_COOKIE_NAME);
	}

	public static String getPassword() {
		return Cookies.getCookie(PASSWORD_COOKIE_NAME);
	}

	public static String getSessionId() {
		return Cookies.getCookie(SESSIONID_COOKIE_NAME);
	}

}